/*
 * File Name：ImageLoaderHelper.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： ImageLoaderHelper.java
 * Modify By：bin
 * Modify Date：2015年1月16日
 * Modify Type：Add
 */
package com.ciwong.mobilelib.utils;

import android.content.Context;
import android.graphics.Bitmap;

import android.widget.ImageView;

import com.ciwong.mobilelib.R;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.File;

/**
 * ImageLoader帮助类
 *
 * @author bin
 * @version ciwong v.1.0 2015年1月16日
 * @since ciwong v.1.0
 */
public class ImageLoaderHelper {
    /**
     * 缓存大小
     */
    public static final int BASE_CACHE_SIZE = 1024 * 1024 * 20;

    /**
     * 缓存图片数量
     */
    public static final int DISC_CACHE_COUNT = 500;

    /**
     * 1024
     */
    public static final int K = 1024;

    /**
     * 10
     */
    public static final int TEN = 10;

    /**
     * 1000
     */
    public static final int THOUSAND = 100;

    private int memoryCacheSize = K * K * TEN;

    private Context mContext;

    private final int two = 2;

    private long discCacheSize = BASE_CACHE_SIZE;

    /**
     * 缓存文件路径
     */
    private String imagesCachePath = BaseSystem.getProjectFolderPath()
            + File.separator + "images";

    /**
     * 缓存文件名
     */
    private FileNameGenerator fileNameGenerator = new Md5FileNameGenerator();

    private static ImageLoaderHelper instance = null;

    private DisplayImageOptions.Builder defDisplayBuilder = new DisplayImageOptions.Builder()
            .cacheInMemory(true).cacheOnDisc(true)
            .showImageForEmptyUri(R.mipmap.lib_default_rect_failed)
            .showImageOnFail(R.mipmap.lib_default_rect_failed)
            .showStubImage(R.mipmap.lib_default_rect);

    private DisplayImageOptions defDisplayOptions = defDisplayBuilder.build();

    private ImageLoaderHelper() {

    }

    public static ImageLoaderHelper getInstance() {
        if (instance == null) {
            syncInit();
        }
        return instance;
    }

    private static void syncInit() {
        if (instance == null) {
            instance = new ImageLoaderHelper();
        }
    }

    private boolean isInited = false;

    public boolean isInited() {
        return isInited;
    }

    public void setInited(boolean inited) {
        isInited = inited;
    }

    /**
     * 初始化ImageLoader
     *
     * @param context 上下文对象
     */
    public void init(Context context) {
        try {
            ImageLoaderConfiguration configuration = getConfigurationBuilder(
                    context).build();
            ImageLoader.getInstance().init(configuration);
            setInited(true);
        } catch (Exception e) {
            setInited(false);
            e.getStackTrace();
        }

    }

    /**
     * 获取ImageLoader配置
     *
     * @param context 上下文对象
     * @return {@linkplain ImageLoaderConfiguration}
     */
    private ImageLoaderConfiguration.Builder getConfigurationBuilder(
            Context context) {
        mContext = context;
        ImageLoaderConfiguration.Builder builder = null;
        try {
            builder = new ImageLoaderConfiguration.Builder(context)
                    .threadPriority(Thread.NORM_PRIORITY - two)
                    .denyCacheImageMultipleSizesInMemory()
                    .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                    .tasksProcessingOrder(QueueProcessingType.LIFO)
                    .writeDebugLogs()
                    .memoryCacheSize(memoryCacheSize)
                    .memoryCache(new WeakMemoryCache())
                    .memoryCacheExtraOptions(THOUSAND, THOUSAND);
            try {
                builder.diskCache(new LruDiskCache(new File(imagesCachePath),
                        fileNameGenerator, discCacheSize));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder;
    }

    public Bitmap displayImage(final String uri, final ImageView mImageView,
                               ImageSize maxSize, DisplayImageOptions options,
                               final ImageLoadingListener listener) {
        return displayImage(uri, mImageView, maxSize, options, listener, false);
    }

    public Bitmap displayImage(final String uri, final ImageView mImageView,
                               ImageSize maxSize, DisplayImageOptions options,
                               final ImageLoadingListener listener, boolean downScale) {
        final ImageLoader imageLoader = ImageLoader.getInstance();
        Bitmap mBitmap = null;
        try {
            imageLoader.displayImage(uri, new ImageViewAware(mImageView),
                    options, listener, null);
        } catch (Exception e) {
            e.getStackTrace();
        }
        return mBitmap;
    }

    /**
     * 获取图片缓存路径
     *
     * @param url 网络图片URL
     * @return 图片缓存地址
     */
    public String getImageCachePath(String url) {
        return getImagePath(url);
    }

    public String getScalImageCachePath(String url, ImageSize maxSize) {
        if (url != null && maxSize != null) {
            return getImagePath(url) + maxSize.getWidth() + "and"
                    + maxSize.getHeight();
        }
        return null;
    }

    /**
     * 获取图片路径
     *
     * @param key 文件名称
     * @return 图片绝对路径
     */
    private String getImagePath(String key) {
        try {
            File file = new File(imagesCachePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File localFile = new File(key);
            if (localFile.exists()) {
                key = BaseConstants.FILE_PREFIX + key;
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return imagesCachePath + File.separator
                + fileNameGenerator.generate(key);
    }
}
